package com.zookeeper.api;

import org.apache.zookeeper.*;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

//持续监听代码
public class ZKClient2 {

//zookeeper集群连接
    private static String connectString =
            "10.90.100.101:2181,10.90.100.102:2181,10.90.100.103:2181";
    //会话超时时间,这里设置2秒为例
    private static int sessionTimeout = 2000;
    private  ZooKeeper zkClient = null;


    @Before
    public  void init() throws Exception {

        //创建ZooKeeper
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                //持续监听
                System.out.println("=========================");
                List<String> children = null;
                try {
                    children = zkClient.getChildren("/guizhou", true);
                    for (String child : children) {
                        System.out.println(child);
                    }

                    System.out.println("=========================");
                } catch (KeeperException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }


            }
        });
    }

    // 创建子节点
    @Test
    public void create() throws Exception {

        // 参数1：要创建的节点的路径； 参数2：节点数据 ； 参数3：节点权限 ；参数4：节点的类型
        String nodeCreated = zkClient.create("/guizhou/guiyang/huaxi", "HX".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }


    // 获取子节点
    @Test
    public void getChildren() throws Exception {
       // 参数1： 监听的路径  参数2：是否监听
        List<String> children = zkClient.getChildren("/guizhou", true);

//        for (String child : children) {
//            System.out.println(child);
//        }

        // 延时阻塞
        Thread.sleep(Long.MAX_VALUE);
    }
}





